package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.domain.Cart;
import csu.web.mypetstore.domain.Order;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class NewOrderFormServlet extends HttpServlet {

    private static final String NEW_ORDER_FROM = "/WEB-INF/jsp/order/newOrder.jsp";
    private static final String SIGN_ON_FORM = "/WEB-INF/jsp/account/signon.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/error.jsp";

    private Account account;
    private Order order;
    private Cart cart;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        account = (Account) session.getAttribute("account");
        cart = (Cart) session.getAttribute("cart");

        if(account == null){
            session.setAttribute("message", "You must log in before placing an order.\nPlease log in and try to place an order");
            resp.sendRedirect("signonForm");
        }else if (cart != null) {
            order = new Order();
            order.initOrder(account, cart);
            List<String> creditCardTypes = new ArrayList<>();
            creditCardTypes.add("Visa");
            creditCardTypes.add("American Express");
            session.setAttribute("creditCardTypes", creditCardTypes);
            session.setAttribute("order", order);
            req.getRequestDispatcher(NEW_ORDER_FROM).forward(req, resp);

        } else {
            session.setAttribute("message", "Cannot create an order because there is no content in the shopping cart!");
            req.getRequestDispatcher(ERROR).forward(req, resp);
            // 显示错误信息
        }

    }

}
